const http = require('http')
const { route } = require('../routes/blog')
const slice = Array.prototype.slice

class LikeExpress {
 constructor() {
   this.routes = {
     all: [],
     get: [],
     post: [],
   }
 }

 /**
  * 判断第一个参数是否为路由 为路由则存储 并将后面的中间件存储起来
  * 第一个参数不为路由 则设置路由为根路由 并将中间件存储起来
  * @param {*} path 
  */
 register(path) {
  // 获取第一个参数path
  const info = {}
  if (typeof path === 'string') {
    info.path = path
    info.stack = slice.call(arguments, 1) // stack最终为一个数组
  } else {
    // 没有路由 则设置为根路由
    info.path = '/'
    info.stack = slice.call(arguments, 0)
  }
  return info
 }

  use() {
    const info = this.register.apply(this, arguments)
    this.routes.all.push(info)
  }
  
  get() {
    const info = this.register.apply(this, arguments)
    this.routes.get.push(info)
  }
  
  post() {
    const info = this.register.apply(this, arguments)
    this.routes.post.push(info)
  }

  match(method, url) {
    let stack = []
    if (url === '/favicon.ico') {
      return stack
    }

    // 获取routes
    let curRoutes = []
    curRoutes = curRoutes.concat(this.routes.all)
    curRoutes = curRoutes.concat(this.routes[method])

    curRoutes.forEach(routeInfo => {
      if (url.indexOf(routeInfo.path) === 0) {
        stack = stack.concat(routeInfo.stack)
      }
    })
    return stack
  }

  handle(req, res, stack) {
    const next = () => {
      const middleware = stack.shift()
      if (middleware) {
        // 执行中间件函数
        middleware(req, res, next)
      }
    }
    next()
  }

  callback() {
    return (req, res) => {
      res.json = (data) => {
        res.setHeader('Content-Type', 'application/json')
        res.end(
          JSON.stringify(data)
        )
      }
      const url = req.url
      const method = req.method.toLowerCase()
      // 单次访问的方法和url
      const resultList = this.match(method, url)
      this.handle(req, res, resultList)
    }
  }

  listen(...args) {
    const server = http.createServer(this.callback())
    server.listen(...args) // 用户调用listen时传入的参数原封不动的传给server.listen
  }
}

// 工厂函数
module.exports = () => {
  return new LikeExpress()
}